﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Home.Haushalt.Lib;
using Home.Haushalt.Lib.Element;
using Infragistics.Win;
using Infragistics.Win.UltraWinGrid;
using System.Drawing;
using System.Windows.Forms;

namespace Home.Haushalt.Gui
{
    /// <summary>
    /// 
    /// </summary>
    public class LayoutController
    {
        /// <summary></summary>
        private static Dictionary<string, UltraGridBand> _bands = new Dictionary<string, UltraGridBand>();

        /// <summary>
        /// 
        /// </summary>
        public static void Reset()
        {
            _bands.Clear();
        }

        /// <summary>
        /// /
        /// </summary>
        /// <param name="elementType"></param>
        /// <param name="table"></param>
        /// <param name="columnSet"></param>
        /// <param name="displayLayout"></param>
        public static void InitColumnLayout(Type elementType, DataTable table, DefaultColumnSets columnSet, UltraGridLayout displayLayout)
        {
            string key = elementType.Name + table.TableName + columnSet.ToString();
            if (_bands.ContainsKey(key))
            {
                displayLayout.BandsSerializer.Add(_bands[key]);
                return; ;
            }

            UltraGridBand ultraGridBand = new UltraGridBand("", -1);
            _bands.Add(key, ultraGridBand);

            displayLayout.BandsSerializer.Add(ultraGridBand);

            ValueList vList = null;
            int sortIndex = 0;
            foreach (DataRow colRow in DAO.GetColumnSettings(elementType, columnSet.ToString()))
            {
                UltraGridColumn gridColumn = null;

                string fieldKey = colRow[Column.Fields.Field].ToString();
                string format = colRow[Column.Fields.Format].ToString();

                if (fieldKey.StartsWith("#"))
                {
                    #region CALCULATED FIELD

                    string columnKey = fieldKey.Replace("#", "");
                    gridColumn = new UltraGridColumn("", 0);
                    gridColumn.Key = columnKey;
                    if (format.Equals("Currency"))
                    {
                        gridColumn.DataType = Type.GetType("System.Double");
                    }
                    else if (format.Equals("Date"))
                    {
                        gridColumn.DataType = Type.GetType("System.DateTime");
                    }
                    else if (format.Equals("Double"))
                    {
                        gridColumn.DataType = Type.GetType("System.Double");
                    }
                    else if (format.Equals("Int"))
                    {
                        gridColumn.DataType = Type.GetType("System.Int32");
                    }
                    else if (format.Equals("Image"))
                    {
                        gridColumn.DataType = typeof(Bitmap);
                    }

                    #endregion CALCULATED FIELD
                }
                else if (colRow[Column.Fields.Formula].ToString().Length > 0)
                {
                    #region FORMULA FIELD

                    string columnKey = fieldKey;
                    gridColumn = new UltraGridColumn("", 0);
                    gridColumn.Key = columnKey;
                    gridColumn.Formula = colRow[Column.Fields.Formula].ToString();

                    #endregion FORMULA FIELD
                }
                else if (fieldKey.Contains(':'))
                {
                    #region VALUE LIST FIELD

                    string columnKey = fieldKey.Split(':')[0];
                    gridColumn = new UltraGridColumn(columnKey);

                    string listName = fieldKey.Split(':')[1];
                    DataRow[] vlDefRows = DAO.Tables[Valuelist.ElementType].Select(string.Format("{0} = '{1}'", Valuelist.Fields.Name, listName));
                    if (vlDefRows.Length > 0)
                    {
                        DataRow vlDefRow = vlDefRows[0];

                        string vlFormat = vlDefRow[Valuelist.Fields.Format].ToString();
                        string vlDM = vlDefRow[Valuelist.Fields.DisplayMember].ToString();
                        string vlVM = vlDefRow[Valuelist.Fields.ValueMemeber].ToString();
                        string vlTbl = vlDefRow[Valuelist.Fields.Table].ToString();

                        ValueListsCollection vlc = displayLayout.Bands[0].Layout.ValueLists;
                        if (!vlc.Exists(listName))
                        {
                            vList = vlc.Add(listName);

                            string[] displFields = vlDM.Split(';');

                            foreach (DataRow vlRow in DAO.Tables[ElementBase.GetType(vlTbl)].Rows)
                            {
                                string displString = "";
                                if (vlFormat.Length > 1)
                                {
                                    string[] displValues = new string[displFields.Length];
                                    for (int i = 0; i < displFields.Length; i++)
                                    {
                                        displValues[i] = vlRow[displFields[i]].ToString();
                                    }
                                    displString = string.Format(vlFormat, displValues).Trim();
                                }
                                else
                                {
                                    displString = vlRow[vlDM].ToString();
                                }
                                vList.ValueListItems.Add(vlRow[vlVM], displString);
                            }
                        }

                        vList = vlc[listName];

                        gridColumn.ValueList = vList;
                        gridColumn.Style = Infragistics.Win.UltraWinGrid.ColumnStyle.Edit;
                    }

                    #endregion VALUE LIST FIELD
                }
                else
                {
                    gridColumn = new UltraGridColumn(fieldKey);
                }

                ultraGridBand.Columns.Add(gridColumn);

                //Header-Caption lokalisierung
                string caption = LO.ColumnName(elementType, columnSet.ToString(), gridColumn.Key);

                if (caption.Length > 0 && caption[0] == '!')
                {
                    caption = LO.ColumnName(elementType, gridColumn.Key);
                }

                gridColumn.Header.Caption = caption;

                //Visible
                bool visible = (colRow[Column.Fields.Visible] == null) || (colRow[Column.Fields.Visible].ToString().Length == 0);
                visible = (visible) ? visible : (colRow[Column.Fields.Visible].ToString().Equals("never", StringComparison.OrdinalIgnoreCase) ? false : colRow[Column.Fields.Visible].ToBool(false));
                gridColumn.Hidden = !visible;

                //Editable
                bool editable = !(colRow[Column.Fields.Editable] == null || colRow[Column.Fields.Editable].ToString().Length == 0 || !colRow[Column.Fields.Editable].ToBool(false));
                if (!editable)
                {
                    gridColumn.CellClickAction = CellClickAction.RowSelect;
                    gridColumn.CellActivation = Activation.ActivateOnly;
                }

                //Width
                int width = (colRow[Column.Fields.Width] == null || colRow[Column.Fields.Width].ToString().Length == 0) ? 50 : colRow[Column.Fields.Width].ToInt();
                gridColumn.Width = width;

                //Sorting
                gridColumn.Header.SetVisiblePosition(sortIndex++, false);

                //Format
                if (format.Equals("Currency"))
                {
                    gridColumn.CellAppearance.TextHAlign = HAlign.Right;
                    gridColumn.Header.Appearance.TextHAlign = HAlign.Right;
                    gridColumn.Format = "C2";
                }
                else if (format.Equals("Double"))
                {
                    gridColumn.CellAppearance.TextHAlign = HAlign.Right;
                    gridColumn.Header.Appearance.TextHAlign = HAlign.Right;
                }
                else if (format.Equals("Date"))
                {
                    gridColumn.CellAppearance.TextHAlign = HAlign.Center;
                    gridColumn.Header.Appearance.TextHAlign = HAlign.Center;
                    gridColumn.Format = "dd.MM.yyyy";
                }
                else if (format.Equals("Int"))
                {
                    gridColumn.CellAppearance.TextHAlign = HAlign.Center;
                    gridColumn.Header.Appearance.TextHAlign = HAlign.Center;
                }
                else if (format.Equals("Image"))
                {
                    gridColumn.CellAppearance.ImageHAlign = Infragistics.Win.HAlign.Center;
                    gridColumn.CellAppearance.ImageVAlign = Infragistics.Win.VAlign.Middle;
                    //gridColumn.Layout.Override.HeaderClickAction = HeaderClickAction.Select;
                    gridColumn.AllowRowFiltering = DefaultableBoolean.False;
                }
                else if (format.Length > 0)
                {
                    gridColumn.Format = format;
                }

                //Align
                string align = colRow[Column.Fields.Align].ToString();
                if (align.Equals(Column.Fields.AlignValueCenter))
                {
                    gridColumn.CellAppearance.TextHAlign = HAlign.Center;
                    gridColumn.Header.Appearance.TextHAlign = HAlign.Center;
                }
                else if (align.Equals(Column.Fields.AlignValueRight))
                {
                    gridColumn.CellAppearance.TextHAlign = HAlign.Right;
                    gridColumn.Header.Appearance.TextHAlign = HAlign.Right;
                }
                else if (align.Equals(Column.Fields.AlignValueLeft))
                {
                    gridColumn.CellAppearance.TextHAlign = HAlign.Left;
                    gridColumn.Header.Appearance.TextHAlign = HAlign.Left;
                }

                //gridColumn.ValueList.ValueListItems.Add("", "(Akt.Wert)");
                // gridColumn.FilterOperandDropDownItems= FilterOperandDropDownItems.
            }


            //nicht definierte Spalten ausgeblendet hinzufügen
            foreach (DataColumn column in table.Columns)
            {

                if (!ultraGridBand.Columns.Exists(column.ColumnName))
                {
                    UltraGridColumn gridColumn = new UltraGridColumn(column.ColumnName);
                    gridColumn.CellClickAction = CellClickAction.RowSelect;
                    gridColumn.CellActivation = Activation.ActivateOnly;
                    gridColumn.Header.Caption = LO.ColumnName(elementType, column.ColumnName);
                    gridColumn.Hidden = true;

                    ultraGridBand.Columns.Add(gridColumn);
                }
            }

            //blankEndColumn
            UltraGridColumn blankGridColumn = new UltraGridColumn("", 0);
            blankGridColumn.Key = "_blank";
            blankGridColumn.Header.Caption = "";
            blankGridColumn.Width = 1;
            blankGridColumn.Header.SetVisiblePosition(ultraGridBand.Columns.Count, false);
            blankGridColumn.CellClickAction = CellClickAction.RowSelect;
            blankGridColumn.CellActivation = Activation.ActivateOnly;
            ultraGridBand.Columns.Add(blankGridColumn);
        }


        /// <summary>
        /// Determines if a control is in design mode, i.e. opened in Visual Studio.
        /// </summary>
        /// <param name="control">The control to be tested.</param>
        /// <returns></returns>
        public static bool IsInDesignMode(System.Windows.Forms.Control control)
        {
            bool retVal = false;
            if ( (control.Site != null && control.Site.DesignMode))
            {
                retVal = true;
            }
            return retVal;
        }
    }
}
